package com.way.fileexplorer;

import java.io.File;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.util.Log;

import com.way.fileexplorer.util.StorageUtil;

public class StorageReceiver extends BroadcastReceiver {

	private static final String TAG = "StorageReceiver";

	/*
	 * 
	 * <receiver android:name="test.spreadtrum.storagemodule.StorageReceiver" >
	 * <intent-filter> <action android:name="android.intent.action.MEDIA_EJECT"
	 * /> <action android:name="android.intent.action.MEDIA_MOUNTED" /> <action
	 * android:name="android.intent.action.MEDIA_BAD_REMOVAL" /> <action
	 * android:name="android.intent.action.MEDIA_UNMOUNTED" />
	 * 
	 * <data android:scheme="file" /> </intent-filter> </receiver>
	 */

	@Override
	public void onReceive(Context context, Intent intent) {
		Log.d(TAG, "StorageReceiver intent: " + intent);
		File storageFile = whichStorage(intent.getData());
		if (storageFile == null) {
			return;
		}
		String path = storageFile.getAbsolutePath();
		String action = intent.getAction();
		SharedPreferences settings = PreferenceManager
				.getDefaultSharedPreferences(context);
		boolean preAvailable = settings.getBoolean(path, false);
		if (Intent.ACTION_MEDIA_MOUNTED.equals(action)) {
			if (!preAvailable) {
				settings.edit().putBoolean(path, true).commit();
				StorageUtil.notifyStorageChanged(path, true);
			}
		} else if (Intent.ACTION_MEDIA_EJECT.equals(action)
				|| Intent.ACTION_MEDIA_UNMOUNTED.equals(action)
				|| Intent.ACTION_MEDIA_BAD_REMOVAL.equals(action)) {
			if (preAvailable) {
				settings.edit().putBoolean(path, false).commit();
				StorageUtil.notifyStorageChanged(path, false);
			}
		}

	}

	private File whichStorage(Uri uri) {
		if (uri == null || uri.getPath() == null) {
			Log.e(TAG, "onReceive, intent.data.path is null");
			return null;
		}
		String path = uri.getPath();
		if (StorageUtil.isInExternalStorage(path)) {
			return StorageUtil.getExternalStorage();
		} else if (StorageUtil.isInInternalStorage(path)) {
			return StorageUtil.getInternalStorage();
		} else if (StorageUtil.isInUSBStorage(path)) {
			return StorageUtil.getUSBStorage();
		} else {
			Log.e(TAG, "can not found the uri: " + uri + " in which storage");
			return null;
		}
	}
}
